<?php
namespace Admin\Controller;

class OutputController extends BaseController{
	public function index(){
		$result = array();
		$dir = ROOT_PATH.'/'.C('OUTPUT_DIR');
		if (is_dir($dir)){
			$all = $temp = array();
			$dirPath = opendir($dir);
			while (!!$dirName = readdir($dirPath)){
				if (!in_array($dirName,array('.','..'))) $all[] = $dirName;
			}
			closedir($dirPath);
			rsort($all);
			$type = array(
				'visit'=>'访问统计',
				'zip'=>'压缩包');
			if ($all){
				foreach ($all as $value){
					$size = filesize($dir.'/'.$value);
					$temp['name'] = $value;
					$temp['size'] = $size<1073741824 ? $size<1048576 ? $size<1024 ? $size.' 字节' : number_format($size/1024,2).' KB' : number_format($size/1048576,2).' MB' : number_format($size/1073741824,2).' GB';
					foreach ($type as $k=>$v){
						if (substr($value,0,strrpos($value,'_')) == $k) $result[$k][$v][] = $temp;
					}
				}
			}
			ksort($result);
		}
		$this->assign('All',$result);
		$this->display();
	}
	
	public function zip(){
		if (IS_POST){
			if (I('post.files')){
				$dir = ROOT_PATH.'/'.C('OUTPUT_DIR');
				$files = '';
				foreach (I('post.files') as $value){
					if (substr($value,0,1)=='.' || strstr($value,'/') || strstr($value,'\\') || strstr($value,'%5C') || strstr($value,'%2F')){
						$this->failed('非法操作！');
					}else{
						$files .= $dir.$value.',';
					}
				}
				import('Yvjie.PclZip');
				$pclZip = new \PclZip($dir.'zip_'.time().'.zip');
				if ($pclZip->create($files,PCLZIP_OPT_REMOVE_PATH,$dir)){
					if (I('post.del')){
						foreach (I('post.files') as $value){
							unlink($dir.$value);
						}
					}
					$this->success(C('PREV_URL'),'文件压缩成功！');
				}else{
					$this->failed('文件压缩失败：'.$pclZip->errorInfo(true));
				}
			}else{
				$this->failed('您未勾选任何文件！');
			}
		}
	}
	
	public function delete(){
		if (IS_POST){
			if (substr(I('get.id'),0,1)=='.' || strstr(I('get.id'),'/') || strstr(I('get.id'),'\\') || strstr(I('get.id'),'%5C') || strstr(I('get.id'),'%2F')) $this->failed('非法操作！');
			$file = ROOT_PATH.'/'.C('OUTPUT_DIR').'/'.I('get.id');
			file_exists($file) ? unlink($file) ? $this->success(I('post.prev'),'文件删除成功！') : $this->failed('文件删除失败！') : $this->failed('不存在此文件！');
		}
		I('get.id') ? $this->confirm('您真的要删除这条数据么？') : $this->failed('非法操作！');
	}
}